package com.qianmang.damawangticket.utils;

import android.Manifest;
import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.GestureDescription;
import android.annotation.TargetApi;
import android.app.Instrumentation;
import android.graphics.Path;
import android.os.Build;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresPermission;

import com.qianmang.damawangticket.bean.AppBean;
import com.qianmang.damawangticket.callback.CallBack;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

/**
 * Author qianmang
 * Date 2019/9/6
 * Mail 527695148@qq.com
 */
public class CommandExecution {
    public static final String TAG = "CommandExecution";

    public final static String COMMAND_SU = "su";
    public final static String COMMAND_SH = "sh";
    public final static String COMMAND_EXIT = "exit\n";
    public final static String COMMAND_LINE_END = "\n";

    /**
     * Command执行结果
     *
     * @author Mountain
     */
    public static class CommandResult {
        public int result = -1;
        public String errorMsg;
        public String successMsg;

        @Override
        public String toString() {
            return "CommandResult{" +
                    "result=" + result +
                    ", errorMsg='" + errorMsg + '\'' +
                    ", successMsg='" + successMsg + '\'' +
                    '}';
        }
    }

    /**
     * 执行命令—单条
     *
     * @param command
     * @param isRoot
     * @return
     */
    public static CommandResult execCommand(String command, boolean isRoot) {
        String[] commands = {command};
        return execCommand(commands, isRoot);
    }

    /**
     * 执行命令-多条
     *
     * @param commands
     * @param isRoot
     * @return
     */
    public static CommandResult execCommand(String[] commands, boolean isRoot) {
        CommandResult commandResult = new CommandResult();
        if (commands == null || commands.length == 0) return commandResult;
        Process process = null;
        OutputStream os = null;
        BufferedReader successResult = null;
        BufferedReader errorResult = null;
        StringBuilder successMsg = null;
        StringBuilder errorMsg = null;
        try {
            process = Runtime.getRuntime().exec(isRoot ? COMMAND_SU : COMMAND_SH);
            os = process.getOutputStream();
            for (String command : commands) {
                if (!TextUtils.isEmpty(command)) {
                    command = command + COMMAND_LINE_END;
                    os.write(command.getBytes(StandardCharsets.UTF_8));
                    os.flush();
                }
            }
            os.write(COMMAND_EXIT.getBytes(StandardCharsets.UTF_8));
            os.flush();
            commandResult.result = process.waitFor();
            //获取错误信息
            successMsg = new StringBuilder();
            errorMsg = new StringBuilder();
            successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
            errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String s;
            while ((s = successResult.readLine()) != null) successMsg.append(s);
            while ((s = errorResult.readLine()) != null) errorMsg.append(s);
            commandResult.successMsg = successMsg.toString();
            commandResult.errorMsg = errorMsg.toString();
            Log.i(TAG, commandResult.result + " | " + commandResult.successMsg
                    + " | " + commandResult.errorMsg);
        } catch (IOException e) {
            String errmsg = e.getMessage();
            if (errmsg != null) {
                Log.e(TAG, errmsg);
            } else {
                e.printStackTrace();
            }
        } catch (Exception e) {
            String errmsg = e.getMessage();
            if (errmsg != null) {
                Log.e(TAG, errmsg);
            } else {
                e.printStackTrace();
            }
        } finally {
            try {
                if (os != null) os.close();
                if (successResult != null) successResult.close();
                if (errorResult != null) errorResult.close();
            } catch (IOException e) {
                String errmsg = e.getMessage();
                if (errmsg != null) {
                    Log.e(TAG, errmsg);
                } else {
                    e.printStackTrace();
                }
            }
            if (process != null) process.destroy();
        }
        return commandResult;
    }

    public static void click(AccessibilityService service, AppBean appBean, int x, int y, @Nullable CallBack callBack) {
        if (x < 0 || y < 0) {
            return;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Path path = new Path();
            path.moveTo(x, y);
            dispatchGestureView(service, appBean, path, callBack);
        } else {
            String com = "input tap " + x + " " + y;
            Log.i("com==", com);
            CommandResult commandResult = execCommand(com, true);
            Log.i("CommandExecution-click", commandResult.toString());

        }
    }

    public static void click(AccessibilityService service, int x, int y, @Nullable CallBack callBack) {
        if (x < 0 || y < 0) {
            return;
        }
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//            Path path = new Path();
//            path.moveTo(x, y);
//            dispatchGestureView(service, null, path, callBack);
//        } else {

        String com = "input touchscreen swipe " + x + " " + y+ " "  + (x + 5) + " " + (y + 10) + " " + 100;
        Log.i("com==", com);
        CommandResult commandResult = execCommand(com, true);
        Log.i("CommandExecution-click", commandResult.toString());

//        }
    }

    //500 1200 500 70
    public static void swipe(int x1, int y1, int x2, int y2) {
        CommandResult commandResult = execCommand(" input swipe " + x1 + " " + y1 + " " + x2 + " " + y2, true);
        Log.i("commandResult =", commandResult.toString());

    }

    //500 1200 500 70
    public static void swipe(AccessibilityService service, AppBean appBean, int x1, int y1, int x2, int y2, int duration, @Nullable CallBack callBack) {
        if (duration < 300) {
            throw new RuntimeException("duration太小，滑动可能会失败");
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            swipe(service, appBean, x1, y1, x2, y2, callBack);
        } else {
            CommandResult commandResult = execCommand(" input swipe " + x1 + " " + y1 + " " + x2 + " " + y2 + " " + duration, true);
            Log.i("commandResult =", commandResult.toString());

        }

    }


    //500 1200 500 70
    public static void swipe(AccessibilityService service, int x1, int y1, int x2, int y2, int duration, @Nullable CallBack callBack) {
        if (duration < 300) {
            throw new RuntimeException("duration太小，滑动可能会失败");
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            swipe(service, null, x1, y1, x2, y2, callBack);
        } else {
            CommandResult commandResult = execCommand(" input swipe " + x1 + " " + y1 + " " + x2 + " " + y2 + " " + duration, true);
            Log.i("commandResult =", commandResult.toString());

        }

    }


    /**
     * 模拟点击事件
     *
     * @param path 路径
     */
    @TargetApi(Build.VERSION_CODES.N)
    private static void dispatchGestureView(AccessibilityService accessibilityService, @Nullable AppBean appBean, Path path, @Nullable CallBack call) {
        GestureDescription.Builder builder = new GestureDescription.Builder();
        builder.addStroke(new GestureDescription.StrokeDescription(path, 0L, 300L));
        GestureDescription gesture = builder.build();
        boolean isSend = accessibilityService.dispatchGesture(gesture, new AccessibilityService.GestureResultCallback() {
            @Override
            public void onCompleted(GestureDescription gestureDescription) {
                super.onCompleted(gestureDescription);
                if (call != null) {
                    call.onCompleted();
                }
            }

            @Override
            public void onCancelled(GestureDescription gestureDescription) {
                super.onCancelled(gestureDescription);
                if (call != null) {
                    if (appBean != null) {
//                        EventBus.getDefault().post(new LogInfo("脚本中止执行，请按home键重新打开" + appBean.getAppName() + "应用"));
                    }
                    call.onCancelled();
                }
            }
        }, null);
    }

    @TargetApi(Build.VERSION_CODES.N)
    private static void swipe(AccessibilityService accessibilityService, AppBean appBean, int x1, int y1, int x2, int y2, @Nullable CallBack call) {
        Path path = new Path();
        path.moveTo(x1, y1);
        path.lineTo(x2, y2);
        dispatchGestureView(accessibilityService, appBean, path, call);
    }

    @RequiresPermission("android.permission.INJECT_EVENTS")
    public static void click(int x, int y) {
        new Thread(() -> {
            try {
                Instrumentation inst = new Instrumentation();
                inst.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(),
                        MotionEvent.ACTION_DOWN, x, y, 0));
                inst.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(),
                        MotionEvent.ACTION_UP, x, y, 0));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

}
